import { craeteEffect, effectTypes } from './helper'
import isPromise from 'is-promise'

/** 
 * 提供一个函数，用于产生call effect 
 * @export
 * @param {function|Array} fn [this, fn]
 * @param {*} args
 */
export function call(fn, ...args) {
    let context = null, // this指向
        func = fn // 要运行的函数
    if (Array.isArray(fn)) {
        const [_this, fun] = fn
        context = fn[0]
        func = fn[1]
    }

    return craeteEffect(effectTypes.CALL, { context, fn: func, args })
}

/**
 * 处理call effect 
 * @export
 * @param {*} env
 * @param {*} effect
 * @param {*} next
 */
export function runCallEffect(env, effect, next) {
    const { store } = env
    const { payload: { context, fn, args } } = effect

    const result = fn.call(context, ...args)
    if (isPromise(result)) {
        result.then(r => next(r), err => next(null, err))
    } else {
        next(result)
    }


}